<template>
  <Fragment>
    <BasicModal
      @register="registerModal"
      :width="popModalFixedWidth"
      dialogStyle="top: 70px"
      :bodyStyle="popBodyStyle"
      :title="modalTitle"
      class="jeecg-online-pop-list-modal"
    >
      <template #footer>
        <div style="display: inline-block; width: calc(100% - 140px); text-align: left">
          <a-button v-if="addAuth" style="border-radius: 50px" type="primary" @click="handleAdd" title=""> 新增记录 </a-button>
        </div>
        <a-button @click="handleCancel"> 关闭 </a-button>
        <a-button v-if="submitDisabled" type="primary" @click="handleSubmit" :loading="submitLoading"> 确定 </a-button>
      </template>
      <template #default>
        <BasicTable @register="registerTable" :rowSelection="rowSelection">
          <template #title>
            <a-input-search v-model:value="searchText" @search="onSearch" placeholder="请输入关键词，按回车搜索" style="width: 100%" />
          </template>
          <template #action="{ record: record2 }">
            <TableAction :actions="getTableAction(record2)" />
          </template>
          <template #fileSlot="{ text: text2 }">
            <span v-if="!text2" style="font-size: 12px; font-style: italic">无文件</span>
            <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download" size="small" @click="downloadRowFile(text2)"> 下载 </a-button>
          </template>
          <template #imgSlot="{ text: text2 }">
            <span v-if="!text2" style="font-size: 12px; font-style: italic">无图片</span>
            <img v-else :src="getImgView(text2)" alt="图片不存在" class="online-cell-image" , @click="viewOnlineCellImage(text2)" />
          </template>
          <template #htmlSlot="{ text: text2 }">
            <div>{{ text2 }}</div>
          </template>
          <template #pcaSlot="{ text: text2 }">
            <div :title="getPcaText(text2)">{{ getPcaText(text2) }}</div>
          </template>
          <template #dateSlot="{ text: text2 }">
            <span>{{ getFormatDate(text2) }}</span>
          </template>
        </BasicTable>
      </template>
    </BasicModal>
    <online-pop-modal :id="id" @register="registerPopModal" @success="handleDataSave" topTip="" />
  </Fragment>
</template>
<script lang="ts">
  import { ref, watch, computed, defineComponent, toRaw } from 'vue';
  import { useModal, useModalInner, BasicModal } from '/@/components/Modal';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import { TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useFixedHeightModal, useTableColumns } from '../../use/useAutoForm';
  import OnlinePopModal from '../../auto/comp/OnlinePopModal.vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useListPage } from '/@/hooks/system/useListPage';

  export default defineComponent({
    name: 'OnlinePopListModal',
    components: {
      BasicModal,
      BasicTable: createAsyncComponent(() => import('/@/components/Table/src/BasicTable.vue'), {
        loading: true,
      }),
      TableAction,
      OnlinePopModal,
    },
    props: {
      id: {
        type: String,
        default: '',
      },
      multi: {
        type: Boolean,
        default: false,
      },
      addAuth: {
        type: Boolean,
        default: true,
      },
    },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const { createMessage: $message } = useMessage();
      const { popModalFixedWidth, resetBodyStyle, popBodyStyle } = useFixedHeightModal();
      const searchText = ref('');
      const modalWidth = ref(800);
      const [registerModal, { closeModal }] = useModalInner(() => {
        searchText.value = '';
        selectedRowKeys.value = [];
        selectedRows.value = [];
        setPagination({ current: 1 });
        reload();
        resetBodyStyle();
      });
      const [registerPopModal2, { openModal: openPopModal2 }] = useModal();
      function handleCancel() {
        closeModal();
      }
      const submitDisabled = computed(() => {
        const arr = selectedRowKeys.value;
        if (arr && arr.length > 0) {
          return false;
        }
        return true;
      });
      const submitLoading = ref(false);
      function handleSubmit() {
        submitLoading.value = true;
        const arr = toRaw(selectedRows.value);
        if (arr && arr.length > 0) {
          emit('success', arr);
          closeModal();
        }
        setTimeout(() => {
          submitLoading.value = false;
        }, 200);
      }
      function queryTableData2(params) {
        const url = '/api-online/online/cgform/api/getData/' + props.id;
        return defHttp.get({ url, params });
      }
      function list(params) {
        params['column'] = 'id';
        return new Promise(async (resolve, _reject) => {
          const aa = await queryTableData2(params);
          resolve(aa);
        });
      }
      const onlineTableContext2 = {
        isPopList: true,
        reloadTable() {
          console.log('reloadTable');
        },
        isTree() {
          return false;
        },
      };
      const extConfigJson2 = ref({});
      const {
        columns: columns2,
        downloadRowFile: downloadRowFile2,
        getImgView: getImgView2,
        getPcaText: getPcaText2,
        getFormatDate: getFormatDate2,
        handleColumnResult: handleColumnResult2,
        hrefComponent: hrefComponent2,
        viewOnlineCellImage: viewOnlineCellImage2,
      } = useTableColumns(onlineTableContext2, extConfigJson2);
      function getColumnList() {
        const url = '/api-online/online/cgform/api/getColumns/' + props.id;
        return new Promise((resolve, reject) => {
          defHttp.get({ url }, { isTransformResponse: false }).then((res) => {
            if (res.success) {
              resolve(res.data);
            } else {
              $message.warning(res.msg);
              reject();
            }
          });
        });
      }
      const modalTitle = ref('');
      watch(
        () => props.id,
        async () => {
          const columnResult = await getColumnList();
          handleColumnResult2(columnResult);
          modalTitle.value = columnResult.description;
        },
        { immediate: true }
      );
      const { tableContext } = useListPage({
        designScope: 'process-design',
        pagination: true,
        tableProps: {
          title: '',
          api: list,
          clickToRowSelect: true,
          columns: columns2,
          showTableSetting: false,
          immediate: false,
          canResize: false,
          showActionColumn: false,
          actionColumn: {
            dataIndex: 'action',
            slots: { customRender: 'action' },
          },
          useSearchForm: false,
          beforeFetch: (params) => {
            return addQueryParams(params);
          },
        },
      });
      const [registerTable, { reload, setPagination }, { rowSelection: rowSelection2, selectedRowKeys, selectedRows }] = tableContext;
      watch(
        () => props.multi,
        (val) => {
          if (val == true) {
            rowSelection2.type = 'checkbox';
          } else {
            rowSelection2.type = 'radio';
          }
        },
        { immediate: true }
      );
      function getTableAction(record2) {
        return [
          {
            label: '编辑',
            onClick: handleUpdate.bind(null, record2),
          },
        ];
      }
      function handleUpdate(record2) {
        console.log('handleUpdate', record2);
      }
      function onSearch() {
        reload();
      }
      const eqConditonTypes = ['int', 'double', 'Date', 'Datetime', 'BigDecimal'];
      function addQueryParams(params) {
        const text2 = searchText.value;
        if (!text2) {
          params['superQueryMatchType'] = 'or';
          params['superQueryParams'] = '';
          return params;
        }
        const arr = columns2.value;
        const conditions = [];
        if (arr && arr.length > 0) {
          for (const item of arr) {
            if (item.dbType) {
              if (item.dbType == 'string') {
                conditions.push({ field: item.dataIndex, type: item.dbType.toLowerCase(), rule: 'like', val: text2 });
              } else if (item.dbType == 'Date') {
                if (text2.length == '2020-10-10'.length) {
                  conditions.push({ field: item.dataIndex, type: item.dbType.toLowerCase(), rule: 'eq', val: text2 });
                }
              } else if (item.dbType == 'Datetime') {
                if (text2.length == '2020-10-10 10:10:10'.length) {
                  conditions.push({ field: item.dataIndex, type: item.dbType.toLowerCase(), rule: 'eq', val: text2 });
                }
              } else if (eqConditonTypes.indexOf(item.dbType)) {
                conditions.push({ field: item.dataIndex, type: item.dbType.toLowerCase(), rule: 'eq', val: text2 });
              } else;
            }
          }
        }
        params['superQueryMatchType'] = 'or';
        params['superQueryParams'] = encodeURI(JSON.stringify(conditions));
        return params;
      }
      function handleAdd() {
        openPopModal2(true, {});
      }
      function handleDataSave(data) {
        console.log('handleDateSave', data);
        const arr = [data];
        emit('success', arr);
        closeModal();
      }
      return {
        registerModal,
        modalWidth,
        handleCancel,
        submitDisabled,
        submitLoading,
        handleSubmit,
        registerTable,
        getTableAction,
        searchText,
        onSearch,
        downloadRowFile: downloadRowFile2,
        getImgView: getImgView2,
        getPcaText: getPcaText2,
        getFormatDate: getFormatDate2,
        hrefComponent: hrefComponent2,
        viewOnlineCellImage: viewOnlineCellImage2,
        rowSelection: rowSelection2,
        modalTitle,
        registerPopModal: registerPopModal2,
        handleAdd,
        reload,
        popModalFixedWidth,
        popBodyStyle,
        handleDataSave,
      };
    },
  });
</script>
<style scoped>
  .online-cell-image {
    height: 25px !important;
    margin: 0 auto;
    max-width: 80px;
    font-size: 12px;
    font-style: italic;
  }
</style>
